import $ from "jquery";
// 一个Upload只能够邦一个按钮

/**
 * 上传文件
 * @param {string}  accept input accept属性
 */

export class UploadItem {
  constructor(accept = "image/*") {
    this.accept = accept;
    this.id = `upload-${UploadItem.id++}`;
  }
  static id = 0;
  id;
  $button;
  $input;
  file_list = [];
  cb_load = () => {};
  addEvent($button) {
    $button.on("click", () => {
      document.getElementById(this.id).click();
    });
    document.getElementById(this.id).addEventListener("change", (event) => {
      console.log("Change");
      this.handleFile(event);
    });
  }
  static render(id, $button, accept) {
    return $button.after(function () {
      return $(
        `<input id="${id}" type="file" accept="${accept}" style="display:none" />`
      );
    });
  }
  render($button) {
    this.$button = $button;
    if (!$button.next().is(`#${this.id}`)) {
      UploadItem.render(this.id, $button, this.accept);
      this.addEvent($button);
    }
    return this;
  }
  onProgress(cb_progress) {
    // 当进度更新就会调用
    this.cb_progress = cb_progress;
  }
  onLoad(cb_load) {
    // 浏览器加载文件之后会调用
    this.cb_load = cb_load;
  }

  handleFile(event) {
    //可接受批量上传文件
    const files = event.target.files;
    this.file_list.push(...files);
    this.cb_load(files);
  }
}
